﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public interface ISkinsListPanel
{
    void OnSelectSkin(int skinId);
    void OnConfirm();
    void OnBuy();
}

public class SkinsListPanel : PanelCommon
{
    public ISkinsListPanel uiListener { get; set; }

    List<SkinsItem> m_Items = new List<SkinsItem>();

    public UITouchObject goBack;

    public Transform itemsParent;
    public SkinsItem skinsItemPref;

    public GameObject buyBtn;

    public override void Awake()
    {
        base.Awake();

        skinsItemPref.gameObject.SetActive(false);
    }

    public void Init(SkinsListVCData data)
    {
        for (int i = 0; i < data.skins.Count; i++)
        {
            var newItem = Instantiate(skinsItemPref, itemsParent);
            newItem.gameObject.SetActive(true);
            newItem.Init(data.skins[i], OnSelectItem, OnConfirm);

            m_Items.Add(newItem);
        }
        OnSelectItem(m_Items.Find(e => e.Id == data.defaultSkin));
       
        m_ToHide = false;

        goBack.onPointerDownBegin = GoBackToBattleUI;
        
          //coinText.Init(MGame.Instance.user.coin,"","",0);

    }

    public void OnBuy()
    {
        uiListener?.OnBuy();
    }

    public void OnConfirm()
    {
        this.uiListener?.OnConfirm();

        GoBackToBattleUI(Vector2.zero);
    }

    void OnSelectItem(SkinsItem skinsItem)
    {
        if (!skinsItem)
            return;

        this.uiListener?.OnSelectSkin(skinsItem.Id);

        this.buyBtn.SetActive(!skinsItem.unlock);

        foreach (var item in m_Items)
        {
            if(item == skinsItem)
                item.selectSign.gameObject.SetActive(true);
            else
                item.selectSign.gameObject.SetActive(false);
        }
    }

    bool m_ToHide;

    void GoBackToBattleUI(Vector2 pos)
    {
        if (m_ToHide)
            return;

        m_ToHide = true;

        //this.m_Controller.parentNav.LoadDisplay<MBattleUIViewController>();
        GetComponentInParent<MBattleSceneController>().ShowBattleUI();
    }

    internal void UpdateSkin(SkinVCData data)
    {
        var item = this.m_Items.Find(e => e.Id == data.skinId);
        if (item)
        {
            item.UpdateSkin(data);

            this.buyBtn.SetActive(!item.unlock);
        }

        this.buyBtn.SetActive(!data.unlock);
    }
}
